<template>
  <div class="audit-history">
    <div class="page-header">
      <h2>审核历史</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="项目类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择项目类型"
            clearable
          >
            <el-option label="纵向课题" value="vertical" />
            <el-option label="横向课题" value="horizontal" />
            <el-option label="学术论文" value="paper" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择审核状态"
            clearable
          >
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="REJECTED" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入项目名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="提交人">
          <el-input
            v-model="searchForm.submitter"
            placeholder="请输入提交人"
            clearable
          />
        </el-form-item>
        <el-form-item label="审核时间">
          <el-date-picker
            v-model="searchForm.auditDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="项目名称" min-width="200" />
        <el-table-column prop="type" label="项目类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitterName" label="提交人" width="120" />
        <el-table-column prop="auditorName" label="审核人" width="120" />
        <el-table-column prop="auditStatus" label="审核结果" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.auditStatus)">
              {{ getStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditTime" label="审核时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.auditTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditComment" label="审核意见" min-width="200">
          <template #default="{ row }">
            <span v-if="row.auditComment">{{ row.auditComment }}</span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="审核详情"
      width="800px"
    >
      <div v-if="currentItem" class="audit-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="项目名称" :span="2">
            {{ currentItem.title }}
          </el-descriptions-item>
          <el-descriptions-item label="项目类型">
            <el-tag :type="getTypeTagType(currentItem.type)">
              {{ getTypeText(currentItem.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核结果">
            <el-tag :type="getStatusType(currentItem.auditStatus)">
              {{ getStatusText(currentItem.auditStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交人">
            {{ currentItem.submitterName }}
          </el-descriptions-item>
          <el-descriptions-item label="审核人">
            {{ currentItem.auditorName }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ formatDate(currentItem.submitTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="审核时间">
            {{ formatDate(currentItem.auditTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="审核意见" :span="2">
            <div class="audit-comment">
              {{ currentItem.auditComment || '无' }}
            </div>
          </el-descriptions-item>

          <!-- 根据类型显示不同的详细信息 -->
          <template v-if="currentItem.type === 'vertical'">
            <el-descriptions-item label="项目级别">
              {{ currentItem.projectLevel }}
            </el-descriptions-item>
            <el-descriptions-item label="总金额">
              {{ currentItem.totalAmount }}万元
            </el-descriptions-item>
            <el-descriptions-item label="批准部门">
              {{ currentItem.approvalDepartment }}
            </el-descriptions-item>
            <el-descriptions-item label="项目负责人">
              {{ currentItem.projectLeader }}
            </el-descriptions-item>
          </template>
          <template v-else-if="currentItem.type === 'horizontal'">
            <el-descriptions-item label="合同金额">
              {{ currentItem.contractAmount }}万元
            </el-descriptions-item>
            <el-descriptions-item label="甲方单位">
              {{ currentItem.partyAName }}
            </el-descriptions-item>
            <el-descriptions-item label="项目负责人">
              {{ currentItem.projectLeader }}
            </el-descriptions-item>
            <el-descriptions-item label="执行负责人">
              {{ currentItem.executionLeader }}
            </el-descriptions-item>
          </template>
          <template v-else-if="currentItem.type === 'paper'">
            <el-descriptions-item label="期刊">
              {{ currentItem.journal }}
            </el-descriptions-item>
            <el-descriptions-item label="检索级别">
              {{ currentItem.indexLevel }}
            </el-descriptions-item>
            <el-descriptions-item label="第一作者">
              {{ currentItem.firstAuthor }}
            </el-descriptions-item>
            <el-descriptions-item label="通讯作者">
              {{ currentItem.correspondingAuthor }}
            </el-descriptions-item>
          </template>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { auditAPI } from '@/api/audit'

export default {
  name: 'AuditHistory',
  components: {
    Search,
    Refresh
  },
  setup() {
    const loading = ref(false)
    const tableData = ref([])
    const detailDialogVisible = ref(false)
    const currentItem = ref(null)

    const searchForm = reactive({
      type: '',
      status: '',
      title: '',
      submitter: '',
      auditDateRange: []
    })

    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.currentPage - 1,
          size: pagination.pageSize,
          ...searchForm
        }

        // 处理日期范围
        if (searchForm.auditDateRange && searchForm.auditDateRange.length === 2) {
          params.startDate = searchForm.auditDateRange[0]
          params.endDate = searchForm.auditDateRange[1]
        }
        delete params.auditDateRange

        const response = await auditAPI.getAuditHistory(params)
        tableData.value = response.data || []
        pagination.total = response.data ? response.data.length : 0
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.currentPage = 1
      loadData()
    }

    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        if (key === 'auditDateRange') {
          searchForm[key] = []
        } else {
          searchForm[key] = ''
        }
      })
      pagination.currentPage = 1
      loadData()
    }

    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadData()
    }

    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      loadData()
    }

    const handleView = (row) => {
      currentItem.value = row
      detailDialogVisible.value = true
    }

    const getTypeText = (type) => {
      const typeMap = {
        vertical: '纵向课题',
        horizontal: '横向课题',
        paper: '学术论文'
      }
      return typeMap[type] || '未知类型'
    }

    const getTypeTagType = (type) => {
      const typeMap = {
        vertical: 'primary',
        horizontal: 'success',
        paper: 'warning'
      }
      return typeMap[type] || 'info'
    }

    const getStatusText = (status) => {
      // 直接返回后端传来的中文状态
      return status || '未知状态'
    }

    const getStatusType = (status) => {
      const typeMap = {
        '已通过': 'success',
        '已拒绝': 'danger',
        '待审核': 'warning'
      }
      return typeMap[status] || 'info'
    }

    const formatDate = (date) => {
      if (!date) return '-'
      return new Date(date).toLocaleString('zh-CN')
    }

    onMounted(() => {
      loadData()
    })

    return {
      loading,
      tableData,
      searchForm,
      pagination,
      detailDialogVisible,
      currentItem,
      loadData,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleView,
      getTypeText,
      getTypeTagType,
      getStatusText,
      getStatusType,
      formatDate
    }
  }
}
</script>

<style lang="scss" scoped>
.audit-history {
  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }

  .text-muted {
    color: #909399;
  }

  .audit-detail {
    .el-descriptions {
      margin-top: 20px;
    }

    .audit-comment {
      padding: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
      min-height: 40px;
      white-space: pre-wrap;
    }
  }
}
</style>
